package com.ken.concurrencystudy.example;

import com.ken.concurrencystudy.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 演示由于cpu缓存带来的可见性问题导致的线程并发不安全
 * @author liushiyu@changingedu.com
 * @date 6/6/2020 16:00
 */
@Slf4j
@NotThreadSafe
public class VisibilityDemo {

    private static final int CORE_POOL_SIZE = 2;
    private static final int MAX_POOL_SIZE = 100;
    private static final int QUEUE_CAPACITY = 100;
    private static final Long KEEP_ALIVE_TIME = 1L;

    private static int count = 0;

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE
                ,MAX_POOL_SIZE
                ,KEEP_ALIVE_TIME, TimeUnit.SECONDS
                ,new ArrayBlockingQueue<Runnable>(QUEUE_CAPACITY));
        for (int i = 0; i < CORE_POOL_SIZE; i++) {
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000; j++) {
                        count +=1;
                    }
                    log.info("count:{}",count);
                }
            });
        }
        threadPoolExecutor.shutdown();
        while (!threadPoolExecutor.isShutdown()){

        }
        log.info("count:{}",count);
        log.info("hello world!");
        System.out.println("hello world!");
    }
}
